/*
* dataview  vue声明周期
* */

import {Dialog, Drawer} from 'element-ui'

const dvVueCycle = {
  created(that) {
    let propViewForm = that.propViewForm
    if (propViewForm) {
      // eslint-disable-next-line import/no-dynamic-require
      require([`@/views/${propViewForm}`], (target) => {
        that.viewForm = target.default
      })
        .catch(() => {
          that.viewForm = null
        })
    }
    // 加载主列表数据
    that.fetchStru()

    if (that.propAutoFetchData === undefined || that.propAutoFetchData === true) {
      // that.handleQueryClick()
    } else {
      that.listLoading = false
    }
  },
  mounted(that) {
    if (that.propAutoFetchData === undefined || that.propAutoFetchData === true) {
      // that.handleQueryClick()
    } else {
      that.listLoading = false
    }
  },

  beforeDestroy(that) {
    //清除 定时刷新数据定时器
    that.autoFetchCycleOp('2', '页面关闭，已销毁定时刷新')
  },

  computed: {
    cpViewFormButtons() {
      let buttons = []
      let {flowNodes, viewFormData, propParentData = {}, viewFormButtons, viewFormStatus, flow} = this
      if (this.cpFormReadonly) { // 只读
        viewFormButtons = viewFormButtons.filter(button => button.key != 'vfb-save' && button.key != 'vfb-add'
          && button.key != 'vfb-cancel' && button.key != 'vfb-delete')
      } else {
        viewFormButtons.forEach((button) => {
          if (!button.order) {
            button.order = 999
          }
        })
      }
      buttons = viewFormButtons.sort((a, b) => a.order - b.order).filter(button => !button.hidden && !button.systemHidden)
      return buttons
    },
    cpViewFormFlowButtons() {
      const buttons = []
      /*if (this.viewFormReadOnly || this.viewFormStatus === 'addnew') {
        return buttons
      }*/
      if (this.viewFormStatus === 'addnew') {
        return buttons
      }
      this.viewFormFlowButtons.sort((a, b) => a.sort - b.sort).forEach((button) => {
        if (this.flow == null || this.viewFormData == null) {
          return
        }
        const filter = button.valueIf.split(',')
        filter.map((value) => {
          let fieldName = this.strings.camelCase(this.flow.fieldName)
          if (value == this.viewFormData[fieldName]) {
            buttons.push(button)
            return true
          }
        })
      })


      return buttons
        .filter((button) => !button.hidden)
        .filter((button) => {
          // 权限过滤
          let { roleCodes: btnRoleCodes, userCodes: btnUserCodes } = button

          //按钮 若没有指定权限，则不需要进行权限筛选了
          if (!btnRoleCodes && !btnUserCodes) return true
          btnRoleCodes = btnRoleCodes || []
          btnUserCodes = btnUserCodes || []

          let { roleCodes = [], code, admin } = this.utils.getCurrentUser()

          //拥有管理员角色的，或者登录账户是admin
          if (admin || code == 'admin') {
            return true
          }
          if (btnUserCodes.includes(code)) {
            return true
          }

          if (roleCodes.some((roleCode) => btnRoleCodes.includes(roleCode))) {
            return true
          }
          return false
        })
    },
    // 过滤掉隐藏的按钮hidden:true
    cpViewButtons() {
      this.viewButtons.forEach((button) => {
        if (!button.order) {
          button.order = 0
        }
      })
      return this.viewButtons.sort((a, b) => a.order - b.order).filter((button) => !button.hidden && button.key != 'vb-refresh')
    },
    cpRowButtons() {
      this.rowButtons.forEach((button) => {
        if (!button.order) {
          button.order = 1
        }
      })
      return this.rowButtons.sort((a, b) => a.order - b.order).filter((button) => !button.hidden)
    },
    cpFilteredButtons() {
      // 依据视图中配置的条件进行过滤

      return (buttons, data, isCpRowButton) => {
        //isCpRowButton
        let rowButtonMaxNumTmp = 20
        let btns = buttons.filter((button) => {
          let isShow = this.isShowButton(button, data, isCpRowButton)
          if (isShow && this.propFilterBtnByData) {
            isShow = this.propFilterBtnByData(button, data)
          }
          if (isShow) {
            if (this.strings.isBlank(button.title)) { //只有图标
              rowButtonMaxNumTmp += 40
            } else {
              rowButtonMaxNumTmp += (this.strings.lengthByte(button.title) * 10)
            }
          }
          return isShow
        })

        //计算行内按钮时，保存行内按钮最大数量，用于计算宽度
        if (isCpRowButton && isCpRowButton == true && rowButtonMaxNumTmp > this.rowButtonMaxNum) {
          if (rowButtonMaxNumTmp < 80) {
            rowButtonMaxNumTmp = 80
          }
          this.rowButtonMaxNum = rowButtonMaxNumTmp
        }
        return btns
      }
    },
    cpShowOperationColumn() {
      for (let i = 0; i < this.rows.length; i += 1) {
        if (this.cpFilteredButtons(this.rowButtons, this.rows[i]).length != 0) {
          return true
        }
      }
      return false
    },
    cpColumns() {
      if (!this.columns) {
        return null
      }
      this.columns = this.columnsOld.filter(item => !item.hidden).sort((c1, c2) => c1.sort - c2.sort)

      //计算未设置宽度的列
      let wholeWidth = $('#mainContainer').clientWidth
      let hadWidth = this.utilNum.sum(this.columns.filter(column => this.strings.isNotBlank(column.width)).map(column => column.width))
      let noWidthColumns = this.columns.filter(column => this.strings.isBlank(column.width))
      if (noWidthColumns && noWidthColumns.length > 0) {
        let setWidth = (wholeWidth - hadWidth) / noWidthColumns
        noWidthColumns.forEach(column => column.width = setWidth)
      }
      if (this.propHideColumns && this.propHideColumns.length > 0) {
        this.columns = this.columns.filter(column => this.propHideColumns.indexOf(column.name) == -1)
      }

      // 隐藏条件
      let hiddenWhen
      let hiddenWhenResult
      this.columns = this.columns.filter( column => {
        hiddenWhen = column.hiddenWhen
        if (this.strings.isBlank(hiddenWhen)) {
          return true
        }
        hiddenWhenResult =  false
        try {
          hiddenWhenResult = eval(hiddenWhen)
        } catch (e) {
          console.error('hiddenWhen格式化失败',hiddenWhen)
          console.error(e)
          hiddenWhenResult =  true
        }
        return  !hiddenWhenResult
      })
      return this.columns
    },
    //计算显示列
    cpTableColumn() {
      if (!this.columns) {
        return null
      }
      this.columns.forEach((item) => {
        item.field = item.name
      })
      let tableColumns = [
        { type: 'seq', width: 50 }
      ]
      if (!this.propHideAllButton && this.showCheckbox) {
        tableColumns.push({ type: 'checkbox', width: 50 })
      }
      tableColumns.push(...this.columns.filter((item) => !item.hidden))
      return tableColumns
    },
    cpToolbarBtn() {
      if (this.cpToolbar != null && this.cpToolbar.buttons && this.cpToolbar.buttons.length > 0) {
        return this.cpToolbar.buttons
      }

      return []
    },
    cpToolbar() {
      if (this.propHideAllButton) {
        return null
      }

      let buttons = []
      //加入流程状态
      if (this.flowNodes.length > 0 && !this.propHidePageSearch && !this.propHideFlowSelect) {
        // this.flowNodes.sort((o1, o2) => global.strings.defaultString(o1.sort, 999) - global.strings.defaultString(o2.sort, 999))
        // this.flowNodes.forEach(flow => {
        //   // 若指定了权限，并且没有指定everyone
        //   let { roleCodes = [], code, admin} = this.utils.getCurrentUser()
        //
        //   if (code != 'admin' && !admin &&  this.strings.isNotBlank(flow.roleCodes)) {
        //     let isHave = false
        //     flow.roleCodes.forEach(flowRoleCode => {
        //       if (roleCodes.includes(flowRoleCode)) {
        //         isHave = true
        //       }
        //     })
        //     if (!isHave) return true
        //   }
        //
        //   if (this.flowNodeValue === flow.value) {
        //     buttons.push({code: 'flow_' + flow.value, name: flow.name + '(' + this.tablePage.totalResult + ')', type: 'text', status: 'flow flow_check'})
        //   } else { //不加数字
        //     buttons.push({code: 'flow_' + flow.value, name: flow.name, type: 'text', status: 'flow'})
        //   }
        // })
      }

      //如果存在一个节点进行了角色过滤，则不显示所有按钮了。此处使用流程显示按钮与流程按钮长度是否一致进行判断
      if (buttons.length > 0 && buttons.length == this.flowNodes.length) {
        // buttons.unshift({code: 'split', name: '|', type: 'text', status: 'flow flow_split'})
        //
        // if (this.strings.isBlank(this.flowNodeValue)) {
        //   buttons.unshift({code: 'flow_', name: '所有(' + this.tablePage.totalResult + ')', type: 'text', status: 'flow flow_all flow_check'})
        // } else { //不加数字
        //   buttons.unshift({code: 'flow_', name: '所有', type: 'text', status: 'flow flow_all'})
        // }
      }


      //仅查询时
      if (this.propOnlyQueryAll) {
        buttons.push({code: 'vb-search', name: '查询', status: 'primary', icon: 'el-icon-search', iconStatic: 'search', sort: -100})
        buttons.push({code: 'vb-reset', name: '重置', status: 'default', icon: 'el-icon-refresh-right', iconStatic: 'reset', sort: -90})
        buttons.push({code: 'vb-toggle', name: '展开查询', status: 'default', icon: 'el-icon-sort', iconStatic: 'toggle', sort: -80})
      } else if (this.propOnlyQuery) {
        buttons.push({code: 'confirm', name: '确认', status: 'success', iconStatic: 'confirm'})
        buttons.push({code: 'vb-search', name: '查询', status: 'primary', icon: 'el-icon-search', iconStatic: 'search', sort: -100})
        buttons.push({code: 'vb-reset', name: '重置', status: 'default', icon: 'el-icon-refresh-right', iconStatic: 'reset', sort: -90})
        buttons.push({code: 'vb-toggle', name: '展开查询', status: 'default', icon: 'el-icon-sort', iconStatic: 'toggle'})
        buttons.push({code: 'close', name: '关闭', status: 'default', iconStatic: 'close'})
        // eslint-disable-next-line no-empty
      }  else if (this.propOnlyQuery2) {
      } else {
        //propShowClose
        if (this.propShowClose) {
          buttons.push({code: 'closeWin', status: 'default', name: '关闭', iconStatic: 'close'})
        }

        this.cpFilteredButtons(this.cpViewButtons, this.viewFormData).forEach(button => {
          let buttonAdd = {code: button.key, name: button.title, status: this.strings.defaultString(button.type, 'primary'), icon: button.icon}
          Object.keys(button).forEach(key => {
            if (buttonAdd[key] == undefined) {
              buttonAdd[key] = button[key]
            }
          })
          if (button.flagPrint) {
            buttonAdd.icon = 'el-icon-printer'
          }
          buttons.push(buttonAdd)
        })

        //导入
        if (this.toolbars.showImport && this.strings.isNotBlank(this.importViewKey)) {
          buttons.push({code: 'importData', name: '导入', status: 'default', iconStatic: 'import'})
        }

        //导出
        if (this.toolbars.showExport) {
          buttons.push({code: 'exportData', name: '导出', status: 'default', iconStatic: 'export'})
        }
        if (this.propFilterBtn) {
          buttons = this.propFilterBtn(buttons)
        }
        //批量流程按钮
        this.viewFormFlowButtons.filter(button => {
          if (!this.flowNodeValue) return false
          if (button.flagBatch != true) return false
          if (this.flowNodeValue != button.valueIf) return false
          // 权限过滤
          let { roleCodes: btnRoleCodes, userCodes: btnUserCodes } = button

          //按钮 若没有指定权限，则不需要进行权限筛选了
          if (!btnRoleCodes && !btnUserCodes) return true
          btnRoleCodes = btnRoleCodes || []
          btnUserCodes = btnUserCodes || []

          let { roleCodes = [], code } = this.utils.getCurrentUser()
          if (btnUserCodes.includes(code)) {
            return true
          }

          if (roleCodes.some((roleCode) => btnRoleCodes.includes(roleCode))) {
            return true
          }
          return false
        }).forEach(button2 => {
          buttons.push({
            code: button2.code,
            name: button2.title,
            status: this.strings.defaultString(button2.type, 'primary'),
            flagBatch: true,
            flagBatch2: button2.flagBatch2 && button2.flagBatch2 == true,
            valueIf: button2.valueIf,
            valueTo: button2.valueTo,
            valueIfTitle: button2.valueIfTitle,
            title: button2.title,
            round: true
          })
        })
      }

      if (this.propFilterBtn) {
        buttons = this.propFilterBtn(buttons)
      }




      // 固定的排序规则
      let toolbtnSortMap =  {
        // 确认
        'confirm': -100,
        // 添加
        'vb-add': -95,
        // 删除
        'vb-delete': -90,
        // 查询
        'vb-search': -80,
        // 重置
        'vb-reset': -70,
        // 切换查询区域
        'vb-toggle': -60,
        // 导入
        'importData': -50,
        // 导出
        'exportData': -40,
      }
      let btnCode
      let status
      buttons.forEach(btn => {
        btnCode = btn.code
        status = btn.status
        if (toolbtnSortMap[btnCode]) {
          btn.order = toolbtnSortMap[btn.code]
        }
        if (global.constCommon.themeList.findIndex(item => item.value == status) == -1) {
          btn.status = global.constCommon.themeList[0].value
        }
      })

      buttons = buttons.sort((o1, o2) => global.strings.defaultString(o1.order,0) - global.strings.defaultString(o2.order,0))


      return {
        buttons,
        refresh: false,
        import: false,
        export: this.toolbars.showExport,
        print: false,
        zoom: this.toolbars.showMaxZoom,
        custom: this.toolbars.showCustom
      }
    },
    cpDefaultSort() {
      if (!this.columns) {
        return {}
      }
      let cols = this.columns.filter((col) => this.strings.isNotBlank(col.defaultSort))

      if (cols.length == 0) {
        return {}
      }
      // 默认排序只允许一列
      return { prop: cols[0].name, order: cols[0].defaultSort }
    },
    cpTableHeight() {
      // const refDom = this.$refs.tbMain.$el
      // const fullHeight = refDom.offsetHeight
      if (this.propHeight) {
        return this.propHeight
      }
      let maxH = document.body.clientHeight - 200
      if (this.propSubHeight) {
        maxH -= this.propSubHeight
      }

      //减去顶部合计高度
      if ((this.formConfig &&  this.formConfig.flagSumTop) || this.sumTopColumns.length > 0) {
        maxH -= 35
      }
      return maxH
    },
    //获取流程检查参数
    cpCheckFlowParam() {
      return this.utils.getCheckFlowParam(this)
    },

    // 日志查询条件
    cpLogWrapper() {
      let wrapper = this.$newWrapper()
      if (!this.viewFormData || !this.primaryKey) {
        wrapper.eq('1', '0')
      } else {
        wrapper.eq('bus_id', this.viewFormData[this.primaryKey])
      }
      return wrapper
    },

    // 操作列区域宽度
    cpColumnOpWidth() {
      // 隐藏或者没有操作按钮
      if (this.propHideAllButton || !this.cpShowOperationColumn) {
        return 0
      }

      // 指定的固定宽度
      if (this.propTableOpWidth) {
        return this.propTableOpWidth
      }

      // 指定的固定宽度
      if (this.formConfig && this.formConfig.tableOpWidth && this.formConfig.tableOpWidth > 0) {
        return this.formConfig.tableOpWidth
      }

      return this.rowButtonMaxNum
    },

    // 弹框尺寸
    cpFormWidthPer() {
      // 隐藏或者没有操作按钮
      if (!this.formConfig || !this.formConfig.formDrawerWidth) {
        return 80
      }
      return this.formConfig.formDrawerWidth
    },

    // 弹框宽度
    cpFormWidthPx() {
      // 隐藏或者没有操作按钮
      if (!this.formConfig || !this.utilNum.isNum(this.formConfig.viewFormWidthPx) || this.formConfig.viewFormWidthPx <= 0) {
        return -1
      }
      return this.formConfig.viewFormWidthPx
    },

    // 弹框高度
    cpFormHeightPx() {
      // 隐藏或者没有操作按钮
      if (!this.formConfig || !this.utilNum.isNum(this.formConfig.viewFormHeightPx) || this.formConfig.viewFormHeightPx <= 0) {
        return -1
      }
      return this.formConfig.viewFormHeightPx
    },

    // 是否不使用默认配置
    cpIsFlagColumnsDefaultConfig() {
      return this.formConfig && this.formConfig.flagColumnsDefaultConfig && (this.formConfig.flagColumnsDefaultConfig == true || this.formConfig.flagColumnsDefaultConfig == 1)
    },

    // 是否显示单选按钮
    cpShowRadiobox() {
      return ((!this.propHideAllButton && this.showRadiobox) || this.propShowRadiobox) && !this.propShowCheckbox
    },

    // 是否显示复选按钮
    cpShowCheckbox() {
      return ((!this.propHideAllButton && this.showCheckbox) || this.propShowCheckbox) && !this.propShowRadiobox
    },

    // 表单是否只读
    cpFormReadonly() {
      let flowReadOnly = null
      if (this.flow && this.flowNodes.length > 0) {
        // 行按钮，依据流程先进行过滤
        let flowField = this.strings.camelCase(this.flow.fieldName)
        let flowNodeValue = this.viewFormData[flowField]
        let node = this.flowNodes.find((node) => node.value == flowNodeValue)
        if (node && !node.flagShowVfbSave) {
          flowReadOnly = true
        } else {
          flowReadOnly = false
        }
      }

      // 调用组件传递的这个属性，优先级最高
      if (this.propOnlyQueryAll) {
        return  true
      }

      // 流程的禁用属性次之
      if (flowReadOnly  != null) {
        return  flowReadOnly
      }

      // 根据行启用编辑条件进行判断
      if (this.formConfig.rowEnableCondition) {
        let result = true
        try {
          let data = this.viewFormData
          result = eval(this.formConfig.rowEnableCondition)
        } catch (e) {
          console.error('行启用编辑条件格式化失败',this.formConfig.rowEnableCondition)
          console.error(e)
          return false
        }
        if (!result) {
          return true
        }
      }
      return this.viewFormReadOnly
    },

    // 是否是新数据
    cpFormNew() {
      return this.strings.isBlank(this.viewFormData[this.primaryKey])
    },

    // 是否隐藏表格
    cpPropTableHide() {
      return this.propTableHide != undefined && this.propTableHide == true
    },

    // 隐藏表格后的提示信息
    cpPropTableHideMsg() {
      return this.strings.defaultIfBlank(this.propTableHideMsg, '请先保存主单据再进行操作')
    },

    // 表单是否自动保存
    cpFormAutoSave() {
      // 隐藏或者没有操作按钮
      if (!this.formConfig || !this.formConfig.viewFormAutoSave) {
        return false
      }
      return true
    },

    // 是否禁用 日期字段初始查询
    cpDisabledDateFirst() {
      // 隐藏或者没有操作按钮
      if (this.formConfig && this.formConfig.disabledDateFirst && this.formConfig.disabledDateFirst == true) {
        return true
      }
      return false
    },

    // 是否自动激活下个单元格
    cpDisabledActiveNext() {
      // 隐藏或者没有操作按钮
      if (this.propDisabledActiveNext && this.propDisabledActiveNext == true) {
        return true
      }
      return false
    },
    cpQueryForm () {
      return this.userQuery
    },
    cpQueryFormLabelWidth() {
      let titleMaxLength = 0
      this.userQuery.forEach(q => {
        let titleNew = this.utilFieldMap.show(q.name, q.title, 'dataview', this.propViewKey)
        titleNew = titleNew.replace(/\(/g, '')
        titleNew = titleNew.replace(/\)/g, '')
        if (this.strings.lengthByte(titleNew) > titleMaxLength) titleMaxLength = this.strings.lengthByte(titleNew)
      })
      let titleWidth = titleMaxLength * 10
      if (titleWidth < 40) titleWidth = 40

      let queryFormLabelWidth = this.formConfig && this.formConfig.queryFormLabelWidth ? this.formConfig.queryFormLabelWidth : 0

      if (queryFormLabelWidth > 0) {
        titleWidth = queryFormLabelWidth
      }
      return titleWidth
    }
  },

  watch: {
    viewFormStatus: {
      immediate: true,
      handler() {
        this.setVFBSystemHidden()
      },
    },
    cpColumns: {
      immediate: true,
      handler() {
        if (this.cpColumns && this.cpColumns.length > 0) {
          if (this.cpColumns.filter(item => !item.isRender) == 0 && !this.isViewReady) {
            this.isViewReady = true
            if (window.dataViewInstList == undefined) {
              window.dataViewInstList = []
            }
            window.dataViewInstList.push(this.getGrid())
            let that = this
            this.$nextTick(() => {
              setTimeout(() => {
                if (false != that.propAutoFetchData && that.isAutoReloadAfterFetchStru) {
                  this.fetchData(this.strings.isNotBlank(that.propPageSize), true)
                } else {
                  this.insertFirst()
                }
                this.$emit('view-ready')
              }, 1000)
            })
          }
        }
      },
    },
    viewFormVisible: {
      handler(newVal) {
        if (this.viewFormVisible == true) {
          this.formShow()
          //清除 定时刷新数据定时器
          this.autoFetchCycleOp('2', '编辑界面打开，已销毁定时刷新')

          //根据配置重置标题
          setTimeout(() => {
            if (this.$refs.viewForm && this.$refs.viewForm.$el) {
              try {
                this.columns.forEach(column => {
                  if ($(this.$refs.viewForm.$el).find('[for="' + column.name + '"]').length > 0) {
                    $(this.$refs.viewForm.$el).find('[for="' + column.name + '"]').text(column.title)
                  }
                })

                global.utilFieldMap.replaceSystemWebFieldShowMap(this, 'viewForm', this.propViewKey)
              } catch (e) {
                console.error(e)
              }
            }
          }, 500)
        } else {
          //清除 定时刷新数据定时器
          this.autoFetchCycleOp('1', '编辑界面关闭，已开启定时刷新')
          this.formHide()
        }
      },
    }
  }
}

export default dvVueCycle
